<?php
namespace core\service;
// +----------------------------------------------------------------------
// | 账号管理服务层
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 Even Yin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Even yin <416467069@qq.com> <13022156261>
// +----------------------------------------------------------------------
use \think\Session as Session;
use \think\Cache   as Cache;
use \think\Db   as Db;
class Account extends BaseService
{
    /* -----------------------------------START------------------------------- */
    /*
    * 构造函数
    */
    public function __construct(){
      parent::__construct();
    }

    public function addUser($data=[]){
      //验证数据
      if(false===$this->model('UserModel')->validate($data,'adduser')){
        $this->error = '数据验证不通过';return false;
      }
      $data['create_time'] = $data['update_time'] = strtotime(date('YmdHis'));
      $data['password'] = md5($data['password']);
       //开启事务
      $this->startTrans();
      try{
        //添加数据
        $res = $this->model('UserModel')->add($data,[],'');
        if(!$res){ throw new Exception($this->error, 1); }
        //获取数据
        $user = $this->model('UserModel')->getInfo(['username'=>$data['username']],'id');
        if(!$user){ throw new Exception($this->error, 1); }
        //添加用户关联数据
        $res = $this->model('UserRelationModel')->add(['uid'=>$user['id']]);
        if(!$res){ throw new Exception($this->error, 1); }
        $this->commit();
        return true;
      }catch(\Exception $e){
        $this->rollback();
        return false;
      }
    }

    function deleteUser($id=''){
      $id = (int)$id;
      if($id===1){
        $this->error = '超级管理员不能删除！';return false;
      }
      $this->startTrans();
      try{
        //添加数据
        $res = $this->model('UserModel')->delete($id);
        if(!$res){ throw new Exception($this->error, 1); }
        $res = $this->model('UserRelationModel')->deleteByCondition(['uid'=>$id]);
        if(!$res){ throw new Exception($this->error, 1); }
        $this->commit();
        return true;
      }catch(\Exception $e){
        $this->rollback();
        return false;
      }
    }
    /* -----------------------------------END------------------------------- */
}
